/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sunspotworld;

import com.sun.spot.io.j2me.radiogram.RadiogramConnection;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;

/**
 *
 * @author seb
 */
public class Connection {

    private int port;
    private boolean clientIsOpen = false;
    private boolean serverIsOpen = false;
    private RadiogramConnection clientConnection;
    private RadiogramConnection serverConnection;
    private String adress;


    public Connection(String adress, int port){
        serverSetup(port);
        clientSetup(adress, port);
        this.adress = adress;
        this.port = port;
    }
    
    private void serverSetup(int port){
        try {
            serverConnection = (RadiogramConnection) Connector.open("radiogram://:" + port);
            serverIsOpen = true;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void clientSetup(String adress, int port){
        try {
            clientConnection = (RadiogramConnection) Connector.open("radiogram://"+ adress +":"+ port );
            clientIsOpen = true;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void sendMessage(String message){
        try {
            Datagram dg = clientConnection.newDatagram(clientConnection.getMaximumLength());
            //Datagram dgreply = clientConnection.newDatagram(clientConnection.getMaximumLength());

            dg.writeUTF(message);
            clientConnection.send(dg);
           System.out.println("Send Message");
            
        } catch (IOException ex) {
            ex.printStackTrace();
        
        }
    }
    
    public String receiveMessage(){
        try {
           Datagram dg = serverConnection.newDatagram(serverConnection.getMaximumLength());

            serverConnection.receive(dg);
            System.out.println("Receiving message");
            return dg.readUTF();
            
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public String getAdress(){
        return adress;
    }

    public int getPort(){
        return port;
    }
}

